package com.reagent.system.entity.excel.filter;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reagent.system.entity.Goods;
import com.reagent.system.entity.Type;
import com.reagent.system.entity.excel.ImportExcel;
import com.reagent.system.service.GoodsService;
import com.reagent.system.service.TypeService;
import com.reagent.utils.CommonUtils;
import com.reagent.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 监听器
 * @ClassNmae: EasyExcelImportFilter
 * @Author: HeYue
 * @DateTime: 2020-11-26 04:33
 **/
@Slf4j
@Component
@Scope("prototype")
public class EasyExcelImportFilter extends AnalysisEventListener<ImportExcel> {
    private static final int BATCH_COUNT = 5; // 每次读取5条
    List<Goods> list = new ArrayList<>();
    @Resource
    private GoodsService goodsService;
    @Resource
    private TypeService typeService;

    @Override
    public void invoke(ImportExcel importExcel, AnalysisContext analysisContext) {
        // 拿到excel表格中的一条数据
        log.info("解析到一条数据:" + importExcel);
        // 将数据存放进Goods对象中
        Goods goods = new Goods();
        Date date = new Date();
        String token = JWTUtils.getCurrentToken();
        DecodedJWT jwt = JWTUtils.verifyToken(token);
        if (!ObjectUtils.isEmpty(jwt)) {
            // 设置默认图片
            goods.setImages(CommonUtils.getServerPath() + "upload/default/default.png")
                    .setStatus(0)
                    .setUpdatetime(date)
                    .setCreatetime(date)
                    .setMid(Integer.parseInt(jwt.getClaim("id").asString()))
                    .setDesc(importExcel.getDesc())
                    .setType(typeService.getBaseMapper().selectOne(new QueryWrapper<Type>().select("*").eq("name",
                            importExcel.getType())).getId())
                    .setPrice(BigDecimal.valueOf(Double.valueOf(importExcel.getPrice())))
                    .setNum(Integer.parseInt(importExcel.getNum()))
                    .setName(importExcel.getName());
            list.add(goods);
            // 每次5条记录向数据库插入一次
            if (list.size() >= BATCH_COUNT) {
                saveData();
                list.clear();
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("存储数据库成功!");

    }

    // 保存方法
    private void saveData() {
        log.info("{}条数据开始存储数据库...", list.size());
        goodsService.saveInfo(list);
        log.info("所有数据解析完成!");
    }
}
